package id.net.iconpln.bb.client.view;

import id.net.iconpln.bb.client.service.MasterRPCService;
import id.net.iconpln.bb.client.service.MasterRPCServiceAsync;
import id.net.iconpln.bb.client.service.PengendalianRPCService;
import id.net.iconpln.bb.client.service.PengendalianRPCServiceAsync;
import id.net.iconpln.bb.client.util.ClientModule;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.core.FastMap;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.GroupingStore;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.StoreEvent;
import com.extjs.gxt.ui.client.store.StoreListener;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.DateTimePropertyEditor;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridGroupRenderer;
import com.extjs.gxt.ui.client.widget.grid.GroupColumnData;
import com.extjs.gxt.ui.client.widget.grid.GroupingView;
import com.extjs.gxt.ui.client.widget.layout.FitData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.toolbar.LabelToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class PageBbPencatatanProduksi extends LayoutContainer {
	private final PengendalianRPCServiceAsync service = GWT.create(PengendalianRPCService.class);
	private final MasterRPCServiceAsync serviceMaster = GWT.create(MasterRPCService.class);
	private Grid grid;
	private ListStore storeResult, storeUnit;
	private ComboBox //cboPembangkit, 
		cboUnit, cboPembangkitFilter, cboBulan, cboTahun;
	private TextField txtPemakaian, txtNoPemakaian;
	private TextArea txtKeterangan;
	private DateField txtTgl;
	private Window window;
	private GroupingStore storePemakaian;
	private Button btnFilter;
	
	@Override
	  protected void onRender(Element parent, int pos) {
	    super.onRender(parent, pos); 
	    setLayout(new FitLayout()); 
	    
	    ContentPanel cp = new ContentPanel();  
	  
	    cp.setHeading("Daftar Produksi");  
	    cp.setFrame(true);  
	    cp.setSize(1030, 600);  
	    cp.setLayout(new RowLayout(Orientation.HORIZONTAL));  
	  
	    ContentPanel cpShip = new ContentPanel();
	    cpShip.setLayout(new FitLayout());
	    cpShip.setHeaderVisible(false);
	    
	    grid = createGrid();
	    grid.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);	
	    ToolBar tbJadwal = new ToolBar();
	    tbJadwal.add(new LabelToolItem("<b>Data Produksi</b>"));
	    tbJadwal.add(new SeparatorToolItem());
	    cpShip.setTopComponent(tbJadwal);
	    cpShip.add(grid);
	    
	    FormPanel panel = createForm();	  
	    cp.add(panel, new RowData(.4, 1));  
	    cp.add(cpShip, new RowData(.6, 1)); 
	    add(cp, new FitData(5)); 
	    
	    getList();
	  }  
	  
	  private FormPanel createForm() {  
		  storeUnit = new ListStore();
		  storeResult = new ListStore();
		  storeResult.addStoreListener(new StoreListener<ModelData>(){
			  @Override
				public void storeAdd(StoreEvent<ModelData> se) {
					// TODO Auto-generated method stub
					super.storeAdd(se);
					MessageBox.alert("Information", se.getModels().get(0).get("message").toString(), null);  
					getList();
			  }			  
		  });
		  
		  ContentPanel p = new ContentPanel();
		  p.setHeaderVisible(false);	    
		  p.setButtonAlign(HorizontalAlignment.RIGHT);  
		  final FormPanel panel = new FormPanel();  
		  panel.setHeaderVisible(false);
	    
		  FieldSet fieldSet2 = new FieldSet();  
		  fieldSet2.setHeading("Pengajuan Pakai");  
		  fieldSet2.setCollapsible(false);
	
		  FormLayout layout2 = new FormLayout();  
		  layout2.setLabelWidth(150);  
		  fieldSet2.setLayout(layout2); 
	    
		  txtNoPemakaian = new TextField();
		  txtNoPemakaian.setName("no_pemakaian");
		  txtNoPemakaian.setFieldLabel("No. Produksi");  
		  txtNoPemakaian.setReadOnly(true);
//		  fieldSet2.add(txtNoPemakaian);
		  Map map = new FastMap();
		  map.put("id_pltu", Registry.get("idPltu"));
		  serviceMaster.getMaster("UNIT", map, new AsyncCallback<List<Map>>() {
			
			@Override
			public void onSuccess(List<Map> result) {
				// TODO Auto-generated method stub
				GWT.log("result : " + result.size());
				storeUnit.removeAll();
				storeUnit.add(ClientModule.setListBaseModelFromListMap(result));
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				GWT.log(caught.getMessage());
			}
		});
		  
		  cboUnit = new ComboBox();
		  cboUnit.setName("unit");
		  cboUnit.setFieldLabel("Unit"); 
		  cboUnit.setEmptyText("Select Unit...");  
		  cboUnit.setDisplayField("unit");  
		  cboUnit.setStore(storeUnit);  
		  cboUnit.setTypeAhead(true);  
		  cboUnit.setTriggerAction(TriggerAction.ALL); 
		  fieldSet2.add(cboUnit);
	    
		  txtTgl = new DateField();  
		  txtTgl.setName("tanggal");
		  txtTgl.setPropertyEditor(new DateTimePropertyEditor("dd/MM/yyyy"));
		  txtTgl.setFieldLabel("Tanggal");  
		  txtTgl.setData("text", "Enter Tanggal");     
		  txtTgl.setValue(new Date());
		  fieldSet2.add(txtTgl);
	    
		  txtPemakaian = new TextField();
		  txtPemakaian.setName("pakai");
		  txtPemakaian.setFieldLabel("Produksi (MWH)");  
		  fieldSet2.add(txtPemakaian);
	    
		  txtKeterangan = new TextArea();
		  txtKeterangan.setName("keterangan");
		  txtKeterangan.setFieldLabel("Keterangan");  
		  fieldSet2.add(txtKeterangan);
	    
		  panel.add(fieldSet2);
		  
		  p.addButton(new Button("Submit", new SelectionListener<ButtonEvent>() {  
			  @Override  
			  public void componentSelected(ButtonEvent ce) {  
				  Map mapParam = new FastMap();
				  mapParam.put("id_pltu", Registry.get("idPltu").toString());
				  mapParam.put("id_unit", cboUnit.getValue().get("id_unit"));
				  mapParam.put("kwh", txtPemakaian.getRawValue());
				  mapParam.put("keterangan", txtKeterangan.getRawValue());
				  mapParam.put("tanggal", txtTgl.getRawValue());
				  mapParam.put("user", Registry.get("whoAmI").toString());
				  mapParam.put("app_access", "WEB");
				  mapParam.put("no_permintaan",txtNoPemakaian.getRawValue());
				  
				  if (txtNoPemakaian.getRawValue().equals("")){
					  mapParam.put("crud", "CREATE");
				  }else{
					  mapParam.put("crud", "UPDATE");
				  }				  
				  service.insertOperatorBB("PRODUKSI", mapParam, new AsyncCallback<List<Map>>() {
					
					@Override
					public void onSuccess(List<Map> result) {
						// TODO Auto-generated method stub
						storeResult.removeAll();
	    				storeResult.add(ClientModule.setListBaseModelFromListMap(result));
	    				
	    				getList();
					}
					
					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						MessageBox.alert("Failed", caught.getMessage(), null);  
					}
				});
			  }  
		  }));  
		  
		  p.addButton(new Button("Reset", new SelectionListener<ButtonEvent>() {  
			  @Override  
			  public void componentSelected(ButtonEvent ce) {  
				  panel.reset();
			  }  
		  }));  

		  panel.add(p);
		      
		  return panel;  
	  }  
	  
	  private Grid createGrid() {  
	    final List<ColumnConfig> columns = new ArrayList<ColumnConfig>(); 	    
	    ColumnConfig end_time = new ColumnConfig("unit", "Unit", 100);
	    columns.add(end_time);
	    
	    ColumnConfig volume_pakai = new ColumnConfig("kwh", "KWH", 150);
	    columns.add(volume_pakai);	  
	    
	    ColumnConfig id_unit = new ColumnConfig("tanggal", "Tanggal", 150);
	    columns.add(id_unit);	  
	   
	    storePemakaian = new GroupingStore();  
	    storePemakaian.setMonitorChanges(true); 
	    storePemakaian.groupBy("tanggal");  
	    
	    final ColumnModel cm = new ColumnModel(columns);
	    
	    grid = new Grid(storePemakaian, cm);
	    grid.setBorders(true);  
	    
	    GroupingView view = new GroupingView();  
	    view.setShowGroupedColumn(false);  
	    view.setForceFit(true);  
	    view.setGroupRenderer(new GridGroupRenderer() {  
	      public String render(GroupColumnData data) {  
	        String f = cm.getColumnById(data.field).getHeader();  
	        String l = data.models.size() == 1 ? "Item" : "Items";  
	        return f + ": " + data.group + " (" + data.models.size() + " " + l + ")";  
	      }  
	    });  
	    
	    grid.setView(view);
	    
	    return grid;  
	  }  
	  
	  private void getList(){
		Map map = new FastMap();
      	map.put("id_pltu", Registry.get("idPltu").toString());
      	map.put("blth", "");
      	map.put("id_unit", "");
      	
      	service.getListProduksi("LIST_PRODUKSI", map, new AsyncCallback<List<Map>>() {
				
				@Override
				public void onSuccess(List<Map> result) {
					// TODO Auto-generated method stub
					storePemakaian.removeAll();
					storePemakaian.add(ClientModule.setListBaseModelFromListMap(result));
				}
				
				@Override
				public void onFailure(Throwable caught) {
					// TODO Auto-generated method stub
					GWT.log(caught.getMessage());
				}
			});
	  }
}
